{% extends "base.html" %}

{% block content %}
<div class="card">
    <h2>管理员指令</h2>
    
    <!-- 标签导航 -->
    <div class="tab-nav">
        {% for cmd_name, cmd_info in commands.items() %}
        <button class="tab-link {% if loop.first %}active{% endif %}" data-tab="{{ cmd_name }}">
            <i class="{{ get_command_icon(cmd_name) }}"></i>
            {{ cmd_info.name }}
        </button>
        {% endfor %}
    </div>
    
    <!-- 指令内容 -->
    <div class="tab-content">
        {% for cmd_name, cmd_info in commands.items() %}
        <div id="{{ cmd_name }}" class="tab-pane {% if loop.first %}active{% endif %}">
            <div class="command-card">
                <div class="command-header">
                    <div class="command-icon">
                        <i class="{{ get_command_icon(cmd_name) }}"></i>
                    </div>
                    <div>
                        <h3>{{ cmd_info.name }}</h3>
                        <p class="command-description">{{ cmd_info.description }}</p>
                    </div>
                </div>
                
                <form class="command-execute-form" data-command="{{ cmd_name }}">
                    {% for param in cmd_info.params %}
                        {% if param.type == "select" %}
                            <div class="form-group">
                                <label for="{{ cmd_name }}_{{ param.key }}">{{ param.name }}</label>
                                <select id="{{ cmd_name }}_{{ param.key }}" name="{{ param.key }}" class="param-select" 
                                    {% if param.get('show_if') %}data-show-if="{{ param.show_if|tojson|forceescape }}"{% endif %}>
                                    {% for option in param.options %}
                                        {% if param.options is mapping %}
                                            <option value="{{ option }}">{{ param.options[option] }}</option>
                                        {% else %}
                                            <option value="{{ option }}">{{ option }}</option>
                                        {% endif %}
                                    {% endfor %}
                                </select>
                            </div>
                        {% else %}
                            <div class="form-group" 
                                {% if param.get('show_if') %}data-show-if="{{ param.show_if|tojson|forceescape }}"{% endif %}>
                                <label for="{{ cmd_name }}_{{ param.key }}">{{ param.name }}</label>
                                <input type="{{ param.type }}" id="{{ cmd_name }}_{{ param.key }}" name="{{ param.key }}" 
                                    {% if param.required %}required{% endif %} placeholder="{{ param.get('placeholder', '') }}">
                            </div>
                        {% endif %}
                    {% endfor %}
                    
                    <div class="form-actions">
                        <button type="button" onclick="executeCommand('{{ cmd_name }}')" class="btn btn-primary">
                            <i class="fas fa-play-circle"></i> 执行指令
                        </button>
                    </div>
                </form>
                
                <div id="{{ cmd_name }}_result" class="command-result" style="display: none;"></div>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

<script>
// 标签切换功能
document.querySelectorAll('.tab-link').forEach(tab => {
    tab.addEventListener('click', function() {
        // 移除所有活动状态
        document.querySelectorAll('.tab-link').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
        
        // 添加当前活动状态
        this.classList.add('active');
        const tabId = this.dataset.tab;
        document.getElementById(tabId).classList.add('active');
    });
});

// 动态显示/隐藏表单字段
document.querySelectorAll('.param-select').forEach(select => {
    select.addEventListener('change', function() {
        const showIf = this.dataset.showIf;
        if (showIf) {
            const conditions = JSON.parse(showIf);
            const parentForm = this.closest('.command-execute-form');
            
            Object.keys(conditions).forEach(key => {
                const value = conditions[key];
                const shouldShow = this.value === value;
                
                parentForm.querySelectorAll(`[data-show-if*="${key}"]`).forEach(el => {
                    if (el !== this) {
                        el.style.display = shouldShow ? 'block' : 'none';
                        if (!shouldShow) {
                            el.querySelector('input, select').value = '';
                        }
                    }
                });
            });
        }
    });
    
    // 触发初始状态
    select.dispatchEvent(new Event('change'));
});

// 执行命令
function executeCommand(cmdName) {
    const form = document.querySelector(`.command-execute-form[data-command="${cmdName}"]`);
    const resultDiv = document.getElementById(`${cmdName}_result`);
    const formData = new FormData(form);
    const data = {command_name: cmdName};
    
    formData.forEach((value, key) => {
        data[key] = value;
    });
    
    resultDiv.style.display = 'none';
    
    // 显示加载状态
    const executeBtn = form.querySelector('button');
    const originalText = executeBtn.innerHTML;
    executeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 执行中...';
    executeBtn.disabled = true;
    
    fetch("{{ url_for('execute_command') }}", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        resultDiv.style.display = 'block';
        if (result.success) {
            resultDiv.innerHTML = `<div class="success">✅ ${result.message}</div>`;
        } else {
            resultDiv.innerHTML = `<div class="error">❌ ${result.error}</div>`;
        }
    })
    .catch(error => {
        resultDiv.style.display = 'block';
        resultDiv.innerHTML = `<div class="error">❌ 请求失败: ${error}</div>`;
    })
    .finally(() => {
        executeBtn.innerHTML = originalText;
        executeBtn.disabled = false;
    });
}
</script>
{% endblock %}
